package com.fjwt.gz.mgr.ctrl.activity;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.core.entity.SysUser;
import com.fjwt.gz.core.model.ApiRes;
import com.fjwt.gz.core.utils.SpringBeansUtil;
import com.fjwt.gz.db.dto.ActivityAwardDTO;
import com.fjwt.gz.db.dto.ActivityDTO;
import com.fjwt.gz.db.entity.ActivityEntity;
import com.fjwt.gz.db.entity.AgentInfoEntity;
import com.fjwt.gz.db.entity.OssRecordEntity;
import com.fjwt.gz.db.vo.ActivityAwardVO;
import com.fjwt.gz.db.vo.ActivityVO;
import com.fjwt.gz.mgr.ctrl.CommonCtrl;
import com.fjwt.gz.service.activity.BaseActivityDTO;
import com.fjwt.gz.service.activity.BaseActivityService;
import com.fjwt.gz.service.impl.ActivityService;
import com.fjwt.gz.service.impl.AgentInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 * 活动管理
 *
 * @Author: Will
 * @Date: 2023-12-29
 * @Version: 1.0
 */
@RestController
@Slf4j
@RequestMapping("/api/activity")
public class ActivityController extends CommonCtrl {

    @Autowired
    private ActivityService activityService;

    @Autowired
    private AgentInfoService agentInfoService;

    /**
     * 状态：草稿
     */
    private final int STATE_DRAFT = 0;

    /**
     * 状态：审批中
     */
    private final int STATE_EXAMINE = 1;

    /**
     * 状态：上线
     */
    private final int STATE_ONLINE = 4;

    /**
     * 状态：下线
     */
    private final int STATE_OFFLINE = 5;

    /**
     * 查询活动列表
     * @return
     */
    @PreAuthorize("hasAnyAuthority('ENT_ACTIVITY_LIST_INFO', 'ENT_ACTIVITY_LIST_ISSUE', 'ENT_ACTIVITY_LIST_GET', 'ENT_ACTIVITY_LIST_OTHER')")
    @GetMapping
    public ApiRes list() {
        ActivityDTO activityDTO = getObject(ActivityDTO.class);
        activityDTO.setSysType(Constants.SYS_ROLE_TYPE.MANAGER);
        log.info("pc端查询活动列表接口调用，请求地址：/api/activity，请求参数：{}", JSONUtil.toJsonStr(activityDTO));
        IPage<ActivityVO> page = activityService.queryListByPcInfo(getIPage(true), activityDTO);
        log.info("pc端查询活动列表接口调用，请求地址：/api/activity，返回结果：{}", JSONUtil.toJsonStr(page));
        return ApiRes.page(page);
    }

    /**
     * 新增活动
     * @return
     */
    @PreAuthorize("hasAnyAuthority('ENT_ACTIVITY_LIST_ADD')")
    @PostMapping("/add")
    public ApiRes add() {
        BaseActivityDTO baseActivityDTO = getObject(BaseActivityDTO.class);
        log.info("pc端新增活动接口调用，请求地址：/api/activity/add，请求参数：{}", JSONUtil.toJsonStr(baseActivityDTO));
        String activityTemplateNo = baseActivityDTO.getActivityTemplateNo();
        if (TextUtils.isEmpty(baseActivityDTO.getActivityName()) || TextUtils.isEmpty(activityTemplateNo)) {
            return ApiRes.customFail("请求参数异常，请检查！");
        }

        if (baseActivityDTO.getState() != null && baseActivityDTO.getState() != STATE_DRAFT) {
            if ( baseActivityDTO.getStartTime() == null || baseActivityDTO.getEndTime() == null ||TextUtils.isEmpty(baseActivityDTO.getAgentNo())) {
                return ApiRes.customFail("请求参数不全，请检查！");
            }
            if (baseActivityDTO.getState() > STATE_EXAMINE) {
                return ApiRes.customFail("非法请求！");
            }
            AgentInfoEntity agentInfo = agentInfoService.getById(baseActivityDTO.getAgentNo());
            if (agentInfo == null) {
                return ApiRes.customFail("所选机构不存在，请检查！");
            } else {
                baseActivityDTO.setAgentNo1(agentInfo.getAgentNo1());
                baseActivityDTO.setAgentNo2(agentInfo.getAgentNo2());
                baseActivityDTO.setAgentNo3(agentInfo.getAgentNo3());
                baseActivityDTO.setAgentNo4(agentInfo.getAgentNo4());
            }
        }

        // 当前登录用户信息
        SysUser sysUser = getCurrentUser().getSysUser();
        long currentUserId = sysUser.getSysUserId();
        baseActivityDTO.setCreatedUid(currentUserId);

        BaseActivityService activityService = SpringBeansUtil.getBean(activityTemplateNo + "Service", BaseActivityService.class);
        activityService.add(baseActivityDTO);
        return ApiRes.ok();
    }

    /**
     * 查看活动详情
     * @param activityId
     * @return
     */
    @PreAuthorize("hasAnyAuthority('ENT_ACTIVITY_LIST_INFO_VIEW')")
    @RequestMapping(value = "/details", method = RequestMethod.GET)
    public ApiRes details(Long activityId,String activityTemplateNo) {
        if (activityId==null|| TextUtils.isEmpty(activityTemplateNo)) {
            return ApiRes.customFail("请求参数异常，请检查！");
        }
        log.info("pc端查看活动详情接口调用，请求地址：/api/activity/details，请求参数：activityId:{},activityTemplateNo:{}", JSONUtil.toJsonStr(activityId),  activityTemplateNo);
        BaseActivityService activityService = SpringBeansUtil.getBean(activityTemplateNo + "Service", BaseActivityService.class);
        BaseActivityDTO detail = activityService.detail(activityId);
        log.info("pc端查看活动详情接口调用，请求地址：/api/activity/details，返回结果：{}", JSONUtil.toJsonStr(detail));
        return ApiRes.ok(detail);
    }

    /**
     * 修改活动
     * @return
     */
    @PreAuthorize("hasAnyAuthority('ENT_ACTIVITY_LIST_INFO_EDIT')")
    @RequestMapping(value = "", method = RequestMethod.PUT)
    public ApiRes update() {
        BaseActivityDTO baseActivityDTO = getObject(BaseActivityDTO.class);
        log.info("pc端修改活动接口调用，请求地址：/api/activity，请求参数：{}", JSONUtil.toJsonStr(baseActivityDTO));
        String activityTemplateNo = baseActivityDTO.getActivityTemplateNo();
        if (TextUtils.isEmpty(baseActivityDTO.getActivityName()) || TextUtils.isEmpty(activityTemplateNo) || baseActivityDTO.getActivityId() == null) {
            return ApiRes.customFail("请求参数异常，请检查！");
        }

        if (baseActivityDTO.getState() != null && baseActivityDTO.getState() != STATE_DRAFT) {
            // TextUtils.isEmpty(baseActivityDTO.getActivityJson())
            if ( baseActivityDTO.getStartTime() == null || TextUtils.isEmpty(baseActivityDTO.getAgentNo())) {
                return ApiRes.customFail("请求参数不全，请检查！");
            }
            AgentInfoEntity agentInfo = agentInfoService.getById(baseActivityDTO.getAgentNo());
            if (agentInfo == null) {
                return ApiRes.customFail("所选机构不存在，请检查！");
            } else {
                baseActivityDTO.setAgentNo1(agentInfo.getAgentNo1());
                baseActivityDTO.setAgentNo2(agentInfo.getAgentNo2());
                baseActivityDTO.setAgentNo3(agentInfo.getAgentNo3());
                baseActivityDTO.setAgentNo4(agentInfo.getAgentNo4());
            }
        }

        baseActivityDTO.setCreatedUid(null);
        BaseActivityService activityService = SpringBeansUtil.getBean(activityTemplateNo + "Service", BaseActivityService.class);
        activityService.update(baseActivityDTO);
        return ApiRes.ok();
    }


    /**
     * 绑卡消费福分数据匹配
     * @return
     */
    @PreAuthorize("hasAnyAuthority('ENT_OPER_TOOL_INFO_MATCH')")
    @PostMapping(value = "/cardConsumptionPoints")
    public ApiRes cardConsumptionPoints() {
        String ossFileUrl = getValStringRequired("ossFileUrl");
        log.info("pc端绑卡消费福分数据匹配接口调用，请求地址：/api/activity/cardConsumptionPoints，请求参数：ossFileUrl:{}", ossFileUrl);
        JSONObject json = activityService.cardConsumptionPoints(ossFileUrl);
        log.info("pc端绑卡消费福分数据匹配接口调用，请求地址：/api/activity/cardConsumptionPoints，返回结果：{}", JSONUtil.toJsonStr(json));
        return ApiRes.ok(json);
    }

    /**
     * 其余福分数据匹配（根据手机号匹配）
     * @return
     */
    @PreAuthorize("hasAnyAuthority('ENT_OPER_TOOL_INFO_MATCH')")
    @PostMapping(value = "/otherPoints")
    public ApiRes otherPoints() {
        String ossFileUrl = getValStringRequired("ossFileUrl");
        log.info("pc端其他福分数据匹配接口调用，请求地址：/api/activity/otherPoints，请求参数：ossFileUrl:{}", ossFileUrl);
        JSONObject json = activityService.otherPoints(ossFileUrl);
        log.info("pc端其他福分数据匹配接口调用，请求地址：/api/activity/otherPoints，返回结果：{}", JSONUtil.toJsonStr(json));
        return ApiRes.ok(json);
    }

    /**
     * 查询一次性派发积分结果文件
     * @return
     */
    @PostMapping(value = "/pointsResultFileUrl")
    public ApiRes pointsResultFileUrl() {
        String type = getValStringRequired("type");
        log.info("pc端查询一次性派发积分结果文件接口调用，请求地址：/api/activity/pointsResultFileUrl，请求参数：type:{}", type);
        List<OssRecordEntity> list = activityService.pointsResultFileUrl(type);
        log.info("pc端查询一次性派发积分结果文件接口调用，请求地址：/api/activity/pointsResultFileUrl，返回结果：{}", JSONUtil.toJsonStr(list));
        return ApiRes.ok(list);
    }


    /**
     * 删除活动
     * @return
     */
    @PreAuthorize("hasAuthority('ENT_ACTIVITY_LIST_INFO_DEL')")
    @RequestMapping(value = "", method = RequestMethod.DELETE)
    public ApiRes delete() {
        ActivityEntity activityEntity = getObject(ActivityEntity.class);
        log.info("pc端删除活动接口调用，请求地址：/api/activity，请求参数：{}", JSONUtil.toJsonStr(activityEntity));
        Long activityId = activityEntity.getActivityId();
        String activityTemplateNo = activityEntity.getActivityTemplateNo();
        if (activityId == null|| TextUtils.isEmpty(activityTemplateNo)) {
            return ApiRes.customFail("请求参数异常，请检查！");
        }

        ActivityEntity entity =activityService.getById(activityId);
        if ( entity== null) {
            return ApiRes.customFail("该记录不存在！");
        }
        if (entity.getState()!=STATE_DRAFT) {
            return ApiRes.customFail("非草稿状态，不能删除！");
        }
        BaseActivityService activityService = SpringBeansUtil.getBean(activityTemplateNo + "Service", BaseActivityService.class);
        activityService.delete(activityId);
        return ApiRes.ok();
    }


    /**
     * 上下线活动
     * @return
     */
    @PreAuthorize("hasAnyAuthority('ENT_ACTIVITY_LIST_INFO_EDIT')")
    @RequestMapping(value = "/state", method = RequestMethod.PUT)
    public ApiRes updateState() {
        ActivityEntity activityEntity = getObject(ActivityEntity.class);
        log.info("pc端上下线活动接口调用，请求地址：/api/activity/state，请求参数：{}", JSONUtil.toJsonStr(activityEntity));
        Long activityId = activityEntity.getActivityId();
        Integer state = activityEntity.getState();
        if (activityId == null || state == null) {
            return ApiRes.customFail("请求参数异常，请检查！");
        }
        if (state != STATE_ONLINE && state != STATE_OFFLINE) {
            return ApiRes.customFail("请求状态异常，请检查！");
        }
        if (STATE_ONLINE == state) {
            activityService.checkActivityCouponThirdParam(activityId);
        }
        ActivityEntity entity = activityService.getById(activityId);
        if (entity == null) {
            return ApiRes.customFail("该记录不存在！");
        }
        if (STATE_ONLINE == state && entity.getState() != Constants.ACTIVITY_STATE.PASS && entity.getState() != Constants.ACTIVITY_STATE.OFFLINE) {
            return ApiRes.customFail("未审批活动不允许上线！");
        }
        entity.setState(state);
        activityService.updateById(entity);
        return ApiRes.ok();
    }

    /**
     * 上传公众号图片素材接口
     */
    @PostMapping("/uploadPicToGzh")
    public ApiRes uploadPicToGzh(){
        String agentNo = getValString("agentNo");
        String imgUrl = getValString("imgUrl");
        if(StringUtils.isEmpty(agentNo) || StringUtils.isEmpty(imgUrl)){
            return ApiRes.customFail("请求参数缺失！");
        }
        log.info("pc端上传公众号图片素材接口调用，请求地址：/api/activity/uploadPicToGzh，请求参数：agentNo:{},imgUrl:{}", agentNo,imgUrl);
        String mediaId = activityService.uploadPicToGzh(agentNo,imgUrl);
        log.info("pc端上传公众号图片素材接口调用，请求地址：/api/activity/uploadPicToGzh，返回结果：{}", mediaId);
        return StringUtils.isNotEmpty(mediaId)?ApiRes.ok(mediaId):ApiRes.customFail("上传公众号图片素材失败！");
    }


    /**
     * 导入定向派券活动名单
     * @return
     */
    @PreAuthorize("hasAnyAuthority('ENT_ACTIVITY_LIST_INFO_IMPT_USER')")
    @PostMapping(value = "/assignImport")
    public ApiRes assignImport() {
        Long activityId = getValLongRequired("activityId");
        String ossFileUrl = getValStringRequired("ossFileUrl");
        String appId = getValStringRequired("appId");
        log.info("导入定向派券活动名单接口:/api/activity/assignImport，参数：活动编号：{}，ossUrl:{}, appid:{}", activityId, ossFileUrl, appId);

        return ApiRes.ok(activityService.assignImport(activityId, ossFileUrl, appId));
    }

    /**
     * 导入一次性派发积分活动
     * @return
     */
    @PreAuthorize("hasAnyAuthority('ENT_OPER_TOOL_INFO_SCORE_DISBT')")
    @PostMapping(value = "/disposableImport")
    public ApiRes disposableImport() {
        String ossFileUrl = getValStringRequired("ossFileUrl");
        String appId = getValStringRequired("appId");
        String name = getValString("name");
        Long activityId = getValLong("activityId");
        if (StringUtils.isEmpty(ossFileUrl) || StringUtils.isEmpty(appId)){
            return ApiRes.customFail("请求参数缺失！");
        }
        if (activityId == null && StringUtils.isEmpty(name)) {
            return ApiRes.customFail("请求参数缺失！");
        }
        log.info("导入一次性派发积分活动参数：ossUrl:{}", ossFileUrl);
        Long sysUserId = getCurrentUser().getSysUserId();

        return ApiRes.ok(activityService.disposableImport(ossFileUrl, appId, sysUserId, name, activityId));
    }

    /**
     * 获取活动奖品列表
     * @return
     */
    @PreAuthorize("hasAnyAuthority('ENT_ACTIVITY_LIST_INFO_PLATE')")
    @PostMapping(value = "/activityAwardList")
    public ApiRes activityAwardList() {
        Long activityId = getValLong("activityId");
        if (activityId == null){
            return ApiRes.customFail("请求参数异常，请检查！");
        }
        return ApiRes.ok(activityService.activityAwardList(activityId));
    }

    /**
     * 获取活动奖品详情数据
     * @return
     */
    @PreAuthorize("hasAnyAuthority('ENT_ACTIVITY_LIST_INFO_PLATE')")
    @PostMapping(value = "/activityAwardDetail")
    public ApiRes activityAwardDetail() {
        ActivityAwardDTO activityAwardDTO = getObject(ActivityAwardDTO.class);
        if (activityAwardDTO == null || activityAwardDTO.getAwardId() == null || activityAwardDTO.getAwardType() == null){
            return ApiRes.customFail("请求参数异常，请检查！");
        }
        return ApiRes.ok(activityService.activityAwardDetail(getIPage(),activityAwardDTO));
    }

}

